<?php
/**
 * @package		简易CMS
 * @subpackage	管理员组管理模块
 * @version		$Id: admincp_admingroup.php 23 2012-06-11 18:04:03Z htmambo@gmail.com $
 * @author		Hoping
 * @copyright	Copyright (C) 2010 Hoping Software Studio.
 */

 if(!defined('IN_JYCMS') || !defined('IN_ADMINCP')) {
	exit('Access Denied');
}

cpheader();

if(!$operation) {
	if(submitcheck('groupsubmit') && $ids = dimplode($_G['gp_delete'])) {
		$gids = array();
		$query = DB::query("SELECT groupid FROM #__common_usergroup WHERE groupid IN ($ids) AND type='special' AND radminid>'0'");
		while($g = DB::fetch($query)) {
			$gids[] = $g['groupid'];
		}
		if($ids = dimplode($gids)) {
			DB::query("DELETE FROM #__common_usergroup WHERE groupid IN ($ids)");
			DB::query("DELETE FROM #__common_usergroup_field WHERE groupid IN ($ids)");
			DB::query("DELETE FROM #__admincp_group WHERE admingid IN ($ids)");
			$newgroupid = DB::result_first("SELECT groupid FROM #__common_usergroup WHERE type='member' AND creditslower>'0' ORDER BY creditslower LIMIT 1");
			DB::query("UPDATE #__common_member SET groupid='$newgroupid', adminid='0' WHERE groupid IN ($ids)", 'UNBUFFERED');
			deletegroupcache($gids);
		}
	}

	$grouplist = array();
	$query = DB::query("SELECT a.*, u.groupid, u.radminid, u.grouptitle, u.stars, u.color, u.icon, u.type FROM #__admincp_group a
			LEFT JOIN #__common_usergroup u ON u.groupid=a.admingid
			ORDER BY u.type, u.radminid, a.admingid");
	while ($group = DB::fetch($query)) {
		$grouplist[$group['groupid']] = $group;
	}

	if(!submitcheck('groupsubmit')) {
		shownav('user', 'Admingroups');
		showsubmenu('Admingroups');
		showtips('admingroup_tips');
		showformheader('admingroup');
		showtableheader('', 'fixpadding');
		showsubtitle(array('', 'usergroups_title', '', 'type', 'admingroup_level', 'usergroups_stars', 'usergroups_color',
		    '<input class="checkbox" type="checkbox" name="gbcmember" onclick="checkAll(\'value\', this.form, \'gbmember\', \'gbcmember\', 1)" /> <a href="javascript:;" onclick="if(getmultiids()) location.href=\''.ADMINSCRIPT.'?action=usergroups&operation=edit&multi=\' + getmultiids();return false;">'.cplang('multiedit').'</a>',
		    '<input class="checkbox" type="checkbox" name="gpcmember" onclick="checkAll(\'value\', this.form, \'gpmember\', \'gpcmember\', 1)" /> <a href="javascript:;" onclick="if(getmultiids()) location.href=\''.ADMINSCRIPT.'?action=admingroup&operation=edit&multi=\' + getmultiids();return false;">'.cplang('multiedit').'</a>',
		));

		foreach((array)$grouplist as $gid => $group) {
			$adminidselect = '<select name="newradminid['.$group['groupid'].']">';
			for($i = 1;$i <= 3;$i++) {
				$adminidselect .= '<option value="'.$i.'"'.($i == $group['radminid'] ? ' selected="selected"' : '').'>'.cplang('usergroups_system_'.$i).'</option>';
			}
			$adminidselect .= '</select>';

			showtablerow('', array('', '', 'class="td23 lightfont"', 'class="td25"', '', 'class="td25"'), array(
				$group['type'] == 'system' ? '' : "<input class=\"checkbox\" type=\"checkbox\" name=\"delete[]\" value=\"$group[groupid]\">",
				$group['grouptitle'],
				"(groupid:$group[groupid])",
				$group['type'] == 'system' ? cplang('inbuilt') : cplang('custom'),
				$group['type'] == 'system' ? cplang('usergroups_system_'.$group['radminid']) : $adminidselect,
				"<input type=\"text\" class=\"txt\" size=\"2\"name=\"group_stars[$group[groupid]]\" value=\"$group[stars]\">",
				"<input type=\"text\" class=\"txt\" size=\"6\"name=\"group_color[$group[groupid]]\" value=\"$group[color]\">",
				"<input class=\"checkbox\" type=\"checkbox\" chkvalue=\"gbmember\" value=\"$group[groupid]\" onclick=\"multiupdate(this)\" /><a href=\"".ADMINSCRIPT."?action=usergroups&operation=edit&id={$group[admingid]}&return=admin\" class=\"act\">".cplang('admingroup_setting_user')."</a>",
				"<input class=\"checkbox\" type=\"checkbox\" chkvalue=\"gpmember\" value=\"$group[groupid]\" onclick=\"multiupdate(this)\" /><a href=\"".ADMINSCRIPT."?action=admingroup&operation=edit&id=$group[admingid]\" class=\"act\">".cplang('admingroup_setting_admin')."</a>"
			));
		}

		showtablerow('', array('class="td25"', '', '', '', 'colspan="6"'), array(
			cplang('add_new'),
			'<input type="text" class="txt" size="12" name="grouptitlenew">',
			'',
			cplang('custom'),
			"<select name=\"radminidnew\"><option value=\"1\">".cplang('usergroups_system_1')."</option><option value=\"2\">".cplang('usergroups_system_2')."</option><option value=\"3\" selected=\"selected\">".cplang('usergroups_system_3')."</option>",
		));
		showsubmit('groupsubmit', 'submit', 'del');
		showtablefooter();
		showformfooter();

	} else {

		foreach((array)$grouplist as $gid => $group) {
			$stars = intval($_G['gp_group_stars'][$gid]);
			$color = dhtmlspecialchars($_G['gp_group_color'][$gid]);
			if($group['color'] != $color || $group['stars'] != $stars || $group['icon'] != $avatar) {
				DB::query("UPDATE #__common_usergroup SET stars='$stars', color='$color' WHERE groupid='$gid'");
			}
		}

		$grouptitlenew = dhtmlspecialchars(trim($_G['gp_grouptitlenew']));
		$radminidnew = intval($_G['gp_radminidnew']);

		foreach((array)$_G['gp_newradminid'] as $groupid => $newradminid) {
			DB::update('common_usergroup', array('radminid' => $newradminid), "groupid='$groupid'");
		}

		if($grouptitlenew && in_array($radminidnew, array(1, 2, 3))) {

			$data = array();
			$usergroup = DB::fetch_first("SELECT * FROM #__common_usergroup WHERE groupid='$radminidnew'");
			foreach ($usergroup as $key => $val) {
				if(!in_array($key, array('groupid', 'radminid', 'type', 'system', 'grouptitle'))) {
					$val = addslashes($val);
					$data[$key] = $val;
				}
			}
			$fielddata = array();
			$usergroup = DB::fetch_first("SELECT * FROM #__common_usergroup_field WHERE groupid='$radminidnew'");
			foreach ($usergroup as $key => $val) {
				if(!in_array($key, array('groupid'))) {
					$val = addslashes($val);
					$fielddata[$key] = $val;
				}
			}

			$adata = array();
			$admingroup = DB::fetch_first("SELECT * FROM #__admincp_group WHERE admingid='$radminidnew'");
			foreach ($admingroup as $key => $val) {
				if(!in_array($key, array('admingid'))) {
					$val = addslashes($val);
					$adata[$key] = $val;
				}
			}

			$data['radminid'] = $radminidnew;
			$data['type'] = 'special';
			$data['grouptitle'] = $grouptitlenew;
			$newgroupid = DB::insert('common_usergroup', $data, 1);
			if($newgroupid) {
				$adata['admingid'] = $newgroupid;
				$fielddata['groupid'] = $newgroupid;
				DB::insert('admincp_group', $adata);
				DB::insert('common_usergroup_field', $fielddata);
			}
		}

		updatecache(array('usergroups', 'admingroups'));

		cpmsg('admingroups_edit_succeed', 'action=admingroup', 'finished');

	}

} elseif($operation == 'edit') {

	$submitcheck = submitcheck('groupsubmit');

	$multiset = 0;
	if(empty($_G['gp_multi'])) {
		$gids = $_G['gp_id'];
	} else {
		$multiset = 1;
		if(is_array($_G['gp_multi'])) {
			$gids = dimplode($_G['gp_multi']);
		} else {
			$_G['gp_multi'] = explode(',', $_G['gp_multi']);
			array_walk($_G['gp_multi'], 'intval');
			$gids = dimplode($_G['gp_multi']);
		}
	}
	if(count($_G['gp_multi']) == 1) {
		$gids = $_G['gp_multi'][0];
		$multiset = 0;
	}

	if(!$submitcheck) {
		if(empty($gids)) {
			$grouplist = "<select name=\"id\" style=\"width: 150px\">\n";
			$query = DB::query("SELECT u.groupid, u.grouptitle FROM #__admincp_group a LEFT JOIN #__common_usergroup u ON u.groupid=a.admingid ORDER BY u.type, u.radminid, a.admingid");
			while($group = DB::fetch($query)) {
				$grouplist .= "<option value=\"$group[groupid]\">$group[grouptitle]</option>\n";
			}
			$grouplist .= '</select>';
			cpmsg('admingroups_edit_nonexistence', 'action=admingroup&operation=edit'.(!empty($highlight) ? "&highlight=$highlight" : ''), 'form', array(), $grouplist);
		}

		$query = DB::query("SELECT a.*, u.radminid, u.grouptitle, u.groupid FROM #__admincp_group a
			LEFT JOIN #__common_usergroup u ON u.groupid=a.admingid
			WHERE a.admingid IN ($gids)");
		if(!DB::num_rows($query)) {
			cpmsg('usergroups_nonexistence', '', 'error');
		} else {
			while($group = DB::fetch($query)) {
				$mgroup[] = $group;
			}
		}

		$query = DB::query("SELECT u.radminid, u.groupid, u.grouptitle FROM #__admincp_group a LEFT JOIN #__common_usergroup u ON u.groupid=a.admingid ORDER BY u.radminid, a.admingid");
		$grouplist = $gutype = '';
		while($ggroup = DB::fetch($query)) {
			$checked = $_G['gp_id'] == $ggroup['groupid'] || in_array($ggroup['groupid'], $_G['gp_multi']);
			if($gutype != $ggroup['radminid']) {
				$grouplist .= '<em><span class="right"><input name="checkall_'.$ggroup['radminid'].'" onclick="checkAll(\'value\', this.form, \'g'.$ggroup['radminid'].'\', \'checkall_'.$ggroup['radminid'].'\')" type="checkbox" class="vmiddle checkbox" /></span>'.
					($ggroup['radminid'] == 1 ? cplang('usergroups_system_1') : ($ggroup['radminid'] == 2 ? cplang('usergroups_system_2') : cplang('usergroups_system_3'))).'</em>';
				$gutype = $ggroup['radminid'];
			}
			$grouplist .= '<input class="left checkbox ck" chkvalue="g'.$ggroup['radminid'].'" name="multi[]" value="'.$ggroup['groupid'].'" type="checkbox" '.($checked ? 'checked="checked" ' : '').'/>'.
				'<a href="###" onclick="location.href=\''.ADMINSCRIPT.'?action=admingroup&operation=edit&switch=yes&id='.$ggroup['groupid'].'&scrolltop=\'+document.documentElement.scrollTop"'.($checked ? ' class="current"' : '').'>'.$ggroup['grouptitle'].'</a>';
		}

		showformheader('', '', 'menuform', 'get');
		showhiddenfields(array('action' => 'admingroup', 'operation' => 'edit'));
		showformfooter();

		if($multiset) {
			showtips('setting_multi_tips');
		}

		showformheader("admingroup&operation=edit&id={$_G['gp_id']}");
		if($multiset) {
			$_G['showsetting_multi'] = 0;
			$_G['showsetting_multicount'] = count($mgroup);
			foreach((array)$mgroup as $group) {
				$_G['showtableheader_multi'][] = '<a href="javascript:;" onclick="location.href=\''.ADMINSCRIPT.'?action=admingroup&operation=edit&id='.$group['groupid'].';return false">'.$group['grouptitle'].'(groupid:'.$group['groupid'].')</a>';
			}
		}
		$mgids = array();
		foreach((array)$mgroup as $group) {
		$_G['gp_id'] = $gid = $group['groupid'];
		$mgids[] = $gid;

		showtableheader();
		showtagheader('tbody', '', true);
		showtitle('admingroup_edit_portalperm');
		showsetting('admingroup_edit_ban_user', 'allowbanusernew', $group['allowbanuser'], 'radio');
		showsetting('admingroup_edit_edit_user', 'alloweditusernew', $group['allowedituser'], 'radio');
		showsetting('admingroup_edit_manage_report', 'managereportnew', $group['managereport'], 'radio');
		showsetting('admingroup_edit_view_ip', 'allowviewipnew', $group['allowviewip'], 'radio');
		showsetting('admingroup_edit_manage_article', array('allowmanagearticlenew', array(
					array(1, cplang('yes'), array('authorized_article' => 'none')),
					array(0, cplang('no'), array('authorized_article' => ''))
				), TRUE), $group['allowmanagearticle'], 'mradio');
		showtagfooter('tbody');
		showtagheader('tbody', 'authorized_article', !$group['allowmanagearticle']);
		showsetting('admingroup_edit_authorized_article', 'allowauthorizedarticlenew', $group['allowauthorizedarticle'], 'radio');
		showtagfooter('tbody');
		showtagheader('tbody', '', true);
		showsetting('admingroup_edit_diy', 'allowdiynew', $group['allowdiy'], 'radio');
		showsetting('admingroup_edit_authorized_block', 'allowauthorizedblocknew', $group['allowauthorizedblock'], 'radio');
		showtagfooter('tbody');
		showtablefooter();

		showsubmit('groupsubmit');

		$_G['showsetting_multi']++;
		}

		if($_G['showsetting_multicount'] > 1) {
			showhiddenfields(array('multi' => implode(',', $mgids)));
			showmulti();
		}
		showformfooter();

	} else {

		if(!$multiset) {
			$_G['gp_multinew'] = array(0 => array('single' => 1));
		}
		foreach((array)$_G['gp_multinew'] as $k => $row) {
		if(empty($row['single'])) {
			foreach((array)$row as $key => $value) {
				$_G['gp_'.$key] = $value;
			}
			$_G['gp_id'] = $_G['gp_multi'][$k];
		}
		$group = $mgroup[$k];

		DB::update('admincp_group', array(
			'allowviewip' => $_G['gp_allowviewipnew'],
			'allowedituser' => $_G['gp_alloweditusernew'],
			'allowbanuser' => $_G['gp_allowbanusernew'],

			'allowmanagearticle' => $_G['gp_allowmanagearticlenew'],
			'allowauthorizedblock' => $_G['gp_allowauthorizedblocknew'],
			'allowauthorizedarticle' => $_G['gp_allowauthorizedarticlenew'],
			'allowdiy' => $_G['gp_allowdiynew'],
			'managereport' => $_G['gp_managereportnew'],
		), "admingid='$_G[gp_id]'");
		}

		updatecache(array('usergroups', 'admingroups'));

		cpmsg('admingroups_edit_succeed', 'action=admingroup&operation=edit&'.($multiset ? 'multi='.implode(',', $_G['gp_multi']) : 'id='.$_G['gp_id']), 'finished');
	}
}

function deletegroupcache($groupidarray) {
	if(!empty($groupidarray) && is_array($groupidarray)) {
		foreach ($groupidarray as $id) {
			if(is_numeric($id) && $id = intval($id)) {
				@unlink(ROOT_PATH.'./data/cache/cache_usergroup_'.$id.'.php');
				@unlink(ROOT_PATH.'./data/cache/cache_admingroup_'.$id.'.php');
			}
		}
	}
}
